package edu.whu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.whu.demo.domain.Commodity;
import edu.whu.demo.dao.CommodityDao;
import edu.whu.demo.domain.Supplier;
import edu.whu.demo.exception.ProductAdminException;
import edu.whu.demo.service.ICommodityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yang hengyi
 * @since 2022-10-24
 */
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityDao, Commodity> implements ICommodityService {
    @Override
    public Commodity addCommodity(@NotNull Commodity commodity) throws ProductAdminException{
        commodity.setId(null);
        if(!save(commodity)){
            throw new ProductAdminException("添加商品失败");
        }
        return commodity;
    }

    @Override
    public Commodity updateCommodity(@NotNull Commodity commodity) throws ProductAdminException{
        if(commodity.getId() != null){
            Optional.ofNullable(getById(commodity.getId()))
                    .orElseThrow(()->new ProductAdminException("没有找到该商品"));
            if(!updateById(commodity)){
                throw new ProductAdminException("更新失败");
            }
            return commodity;
        }
        else{
            throw new RuntimeException();
        }
    }

    @Override
    public void deleteCommodity(long id) {
        Optional.ofNullable(getById(id))
                .orElseThrow(()->new RuntimeException());
        if(!removeById(id)){
            throw new RuntimeException();
        }

    }

    @Override
    public Page<Commodity> findCommodity(@NotNull Map<String, Object> conditions, @NotNull Page page) {
        LambdaQueryWrapper<Commodity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(conditions.containsKey("name"), Commodity::getName, conditions.get("name"))
                .le(conditions.containsKey("price"), Commodity::getPrice, conditions.get("price"))
                .ge(conditions.containsKey("number"), Commodity::getNumber, conditions.get("number"));
        return getBaseMapper().selectPage(page, lqw);
    }
}
